/*
 Copyright 2007 Ole Rogeberg

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package org.lifeyears.services;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.lifeyears.common.AssertArg;
import org.lifeyears.model.AbstractEntity;
import org.lifeyears.model.AbstractEternalEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * Base class for all services which provides DAO-operation for an entity class.
 *
 * @author Aleksander Blomskøld
 */
@SuppressWarnings( "unchecked" )
@Repository
public abstract class AbstractGenericDAOServiceHibernate<T extends AbstractEntity>
    implements GenericDAOService<T>
{

    private final Logger log = LoggerFactory.getLogger( AbstractGenericDAOServiceHibernate.class );

    @Autowired
    private SessionFactory sessionFactory;

    // the intuitive clazz = T.class doesn't work, so a more funky statement is needed
    protected final Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

    protected Session getSession()
    {
        return this.sessionFactory.getCurrentSession();
    }

    @Override
    @Transactional
    public void delete( final Long id )
    {
        AssertArg.notNull( "id", id );
        delete( get( id ) );
    }

    @Override
    @Transactional
    public void delete( final T entity )
    {
        AssertArg.notNull( "entity", entity );
        log.trace( "Deleting entity {}", entity );
        if ( entity instanceof AbstractEternalEntity )
        {
            final AbstractEternalEntity abstractEternalEntity = (AbstractEternalEntity) entity;
            abstractEternalEntity.setDeleted( true );
            getSession().update( abstractEternalEntity );

        }
        else
        {
            getSession().delete( entity );
        }
    }

    @SuppressWarnings( "unchecked" )
    @Override
    @Transactional( readOnly = true )
    public T get( final Long id )
    {
        AssertArg.notNull( "id", id );
        log.trace( "Loading entity of class {} with id {}.", this.clazz, id );
        final T t = (T) getSession().get( this.clazz, id );
        if ( t instanceof AbstractEternalEntity )
        {
            final AbstractEternalEntity abstractEternalEntity = (AbstractEternalEntity) t;
            if ( abstractEternalEntity.isDeleted() )
            {
                log.debug( "Entity {} deleted, returning null", t );
                return null;
            }
        }

        return t;
    }

    @SuppressWarnings( "unchecked" )
    @Override
    @Transactional( readOnly = true )
    public List<T> getAllList()
    {
        final Criteria criteria = getSession().createCriteria( this.clazz );

        return criteria.list();
    }

    @Override
    @Transactional
    public void save( final T entity )
    {
        AssertArg.notNull( "entity", entity );
        log.trace( "Saving {}", entity );
        getSession().save( entity );
    }

    public void setSessionFactory( final SessionFactory sessionFactory )
    {
        this.sessionFactory = sessionFactory;
    }

    @Override
    @Transactional
    public void update( final T entity )
    {
        AssertArg.notNull( "entity", entity );
        log.trace( "Updating {}", entity );
        getSession().update( entity );
    }
}
